﻿/* 
    require: relyons.js
*/

etui.n.type = function (obj) {
    var typ = Object.prototype.toString.call(obj);
    var closingIndex = typ.indexOf(']');
    return typ.substring(8, closingIndex);
};
etui.util = etui.util || {};
(function ($, ns) {
    function Url(str) {
        if (etui.n.type(str) != "String") {
            throw "etui.util.Url has to be passed in a String as its value";
        }
        this.value = str;
        this._data = {
        // domain -- Domain Object
        // it would be generated once getDomain been called

        // params -- {firstParamName:firstParamValue, secondParamName: secondParamValue}
        // it would be generated once getAllParam been called
    };
}

var hostnameRegex = /^(\w+:\/\/)?([^:\/]*)/;

Url.prototype.getDomain = function () {
    var domainParts, results;
    if (!this._data.domain) {
        results = hostnameRegex.exec(this.value);
        domainParts = results[results.length - 1];
        this._data.domain = new Domain(domainParts);
    }
    return this._data.domain;
}

Url.prototype.initParams = function () {
    var match;
    var params = this._data.params = new Param();
    var regex = /\b(\w+)=([^&#]+)/ig;
    while (match = regex.exec(this.value)) {
        params.value(decodeURIComponent(match[1].valueOf()), decodeURIComponent(match[2]));
    }
};

Url.prototype.param = function (queryParam, value) {
    queryParam = queryParam.toLowerCase();
    return this.paramCS.apply(this, arguments);
};
//
// CS stands for Case Sensitive
//
Url.prototype.paramCS = function (queryParam, value) {
    var allParams;
    if (!this._data.params) {
        this.initParams();
    }
    allParams = this._data.params;
    return allParams.value.apply(allParams, arguments);
};
Url.prototype.toString = function () {
};

function Domain(str) {
    this.value = str;
}
Domain.prototype.getParentDomain = function () {
    var domainParts = this.value.split(".");
    domainParts.shift();
    return new Domain(domainParts.join("."));
};
Domain.prototype.toString = function () {
    return this.value;
}

function Param() {
    this.values = {};
}
Param.prototype.value = function (paramName, paramValue) {
    if (arguments.length == 2) {
        paramValue == null ? delete this.values[paramName] : this.values[paramName] = paramValue;
    }
    return this.values[paramName];
};
Param.prototype.toString = function () {
    var values = this.values, results = [];
    for (var name in values) {
        if (values.hasOwnProperty(name)) {
            results.push(name + "=" + values[name]);
        }
    }
    return results.join("&");
};
ns.Url = Url;
ns.Domain = Domain;
ns.Param = Param;
})(jQuery, etui.util);